package com.strato.datafactory.v1_0_0.activator;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.datafactory.v1_0_0.factory.XmlDefineDataFactory;
import com.strato.datafactory.v1_0_0.factory.provider.DataDefineProviderFactory;

public class Activator implements BundleActivator {

	private static BundleContext context;

	private static DataDefineProviderFactory providerFactory;
	
	@Override
	public void start(BundleContext bundleContext) throws Exception {
		context=bundleContext;
		providerFactory=new DataDefineProviderFactory();
		XmlDefineDataFactory dataFactory=new XmlDefineDataFactory(providerFactory);
		bundleContext.addBundleListener(providerFactory);
		BundleUtil.exportServices(bundleContext, dataFactory, null, null);
		initScan();
	}

	private void initScan() {
		Bundle[] bundles = context.getBundles();
		for(Bundle bundle:bundles){
			if(bundle.getState()==Bundle.ACTIVE||bundle.getState()==Bundle.RESOLVED){
				providerFactory.onResolved(bundle);
			}
		}
	}

	@Override
	public void stop(BundleContext bundleContext) throws Exception {
		if(providerFactory!=null){
			bundleContext.removeBundleListener(providerFactory);
			providerFactory=null;
		}
		context=null;
	}

	public static BundleContext getContext() {
		return context;
	}

}
